# -*- coding: utf-8 -*-
"""
牌局信息
"""
import json
import logging
import datetime

from django.utils.encoding import smart_unicode
from django.views.generic import TemplateView
from django.utils.decorators import method_decorator
from django.views.decorators.http import require_GET, require_POST
from common.game.model import BullPart, LotteryPart, KfcRecord, GuessFruitParticipate

from common.game import db
from common.utils import tz
from common.utils.decorator import response_wrapper
from common.utils.api import token_required
from common.lottery.__init__ import GAME_TYPE
from common.utils.exceptions import ParamError

_LOGGER = logging.getLogger(__name__)


class BullView(TemplateView):

    def get(self, req):
        query_dct = req.GET.dict()
        room = int(query_dct.get('room', 0))
        items, total_count = db.list_bull(query_dct)
        resp_items = []
        for item in items:
            data = item.as_dict()
            for k in ('updated_at', 'created_at'):
                if k in data:
                    data[k] = tz.utc_to_local_str(data[k])
            for k in ('start_ts', 'announce_ts'):
                if k in data:
                    data[k] = tz.ts_to_local_date_str(data[k], f='%Y-%m-%d %H:%M:%S')
            data['room'] = room
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items)}

    def post(self, req):
        pass

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(BullView, self).dispatch(*args, **kwargs)


class BullPartView(TemplateView):

    def get(self, req):
        query_dct = req.GET.dict()
        room = int(query_dct.get('room', 0))
        items, total_count = db.list_bull_part(query_dct)
        resp_items = []
        for item in items:
            data = item.as_dict()
            for k in ('updated_at', 'created_at'):
                if k in data:
                    data[k] = tz.utc_to_local_str(data[k])
            data['room'] = room
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items)}

    def post(self, req):
        pass

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(BullPartView, self).dispatch(*args, **kwargs)


class GameLotteryView(TemplateView):

    def get(self, req):
        query_dct = req.GET.dict()
        items, total_count = db.list_lottery(query_dct)
        resp_items = []
        for item in items:
            data = item.as_dict()
            for k in ('updated_at', 'created_at'):
                if k in data:
                    data[k] = tz.utc_to_local_str(data[k])
            for k in ('start_ts', 'announce_ts'):
                if k in data:
                    data[k] = tz.ts_to_local_date_str(data[k], f='%Y-%m-%d %H:%M:%S')
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items)}

    def post(self, req):
        pass

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(GameLotteryView, self).dispatch(*args, **kwargs)


class GameLotteryPartView(TemplateView):

    def get(self, req):
        query_dct = req.GET.dict()
        items, total_count = db.list_lottery_part(query_dct)
        resp_items = []
        for item in items:
            data = item.as_dict()
            for k in ('updated_at', 'created_at'):
                if k in data:
                    data[k] = tz.utc_to_local_str(data[k])
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items)}

    def post(self, req):
        pass

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(GameLotteryPartView, self).dispatch(*args, **kwargs)


@require_POST
@response_wrapper
@token_required
def fresh_lottery_part(req, part_id):
    make_award = db.fresh_lottery_part(part_id)
    if make_award:
        return {
            'award': make_award
        }
    else:
        return {}


@require_POST
@response_wrapper
@token_required
def fresh_bull_part(req, part_id):
    db.fresh_bull_part(part_id)
    return {}


@require_GET
@response_wrapper
@token_required
def get_fruit_list(req):
    query_dct = req.GET.dict()
    items, total_count = db.list_fruit(query_dct)
    resp_items = []
    for item in items:
        data = item.as_dict()
        for k in ('updated_at', 'created_at'):
            if k in data:
                data[k] = tz.utc_to_local_str(data[k])
        for k in ('start_ts', 'announce_ts'):
            if k in data:
                data[k] = tz.ts_to_local_date_str(data[k], f='%Y-%m-%d %H:%M:%S')
        resp_items.append(data)

    return {'list': resp_items, 'page': query_dct.get('$page', 1),
            'total_count': total_count, 'size': len(resp_items)}


@require_GET
@response_wrapper
@token_required
def get_fruit_part(req):
    query_dct = req.GET.dict()
    items, total_count = db.list_fruit_part(query_dct)
    resp_items = []
    for item in items:
        data = item.as_dict()
        for k in ('updated_at', 'created_at'):
            if k in data:
                data[k] = tz.utc_to_local_str(data[k])
        resp_items.append(data)

    return {'list': resp_items, 'page': query_dct.get('$page', 1),
            'total_count': total_count, 'size': len(resp_items)}


def get_is_adjust(extend):
    if extend is not None:
        json_extend = json.loads(extend)
        if u'is_adjust' in json_extend:
            if json_extend[u'is_adjust']:
                return u"(已调整)"
            else:
                return u"(未调整)"
    return ""


def get_casino_records_lotter(query_dct):
    items, total_count, bet_total, award_total = db.game_table_list(query_dct, LotteryPart)
    resp_items = []
    for item in items:
        data = item.as_dict()
        for k in ('updated_at', 'created_at'):
            if k in data:
                data[k] = tz.utc_to_local_str(data[k])
        data['type'] = GAME_TYPE.WHEEL;
        data['ad_status'] = get_is_adjust(data['extend'])
        resp_items.append(data)

    return {'list': resp_items, 'page': query_dct.get('$page', 1),
            'total_count': total_count, 'size': len(resp_items),
            'bet_total': bet_total, 'award_total': award_total}


def get_casino_records_bull(query_dct):
    items, total_count, bet_total, award_total = db.game_table_list(query_dct, BullPart)
    resp_items = []
    for item in items:
        data = item.as_dict()
        for k in ('updated_at', 'created_at'):
            if k in data:
                data[k] = tz.utc_to_local_str(data[k])
        data['type'] = GAME_TYPE.BULL;
        data['ad_status'] = get_is_adjust(data['extend'])
        resp_items.append(data)
        
    return {'list': resp_items, 'page': query_dct.get('$page', 1),
            'total_count': total_count, 'size': len(resp_items),
            'bet_total': bet_total, 'award_total': award_total}


def get_casino_records_kfc(query_dct):
    items, total_count, bet_total, award_total = db.game_table_list(query_dct, KfcRecord)
    resp_items = []
    for item in items:
        data = item.as_dict()
        for k in ('updated_at', 'created_at'):
            if k in data:
                data[k] = tz.utc_to_local_str(data[k])
        data['type'] = GAME_TYPE.CHICKEN;
        data['ad_status'] = get_is_adjust(data['extend'])
        resp_items.append(data)

    return {'list': resp_items, 'page': query_dct.get('$page', 1),
            'total_count': total_count, 'size': len(resp_items),
            'bet_total': bet_total, 'award_total': award_total}


def get_casino_records_fruit(query_dct):
    items, total_count, bet_total, award_total = db.game_table_list(query_dct, GuessFruitParticipate)
    resp_items = []
    for item in items:
        data = item.as_dict()
        for k in ('updated_at', 'created_at'):
            if k in data:
                data[k] = tz.utc_to_local_str(data[k])
        data['type'] = GAME_TYPE.FRUIT;
        data['ad_status'] = get_is_adjust(data['extend'])
        resp_items.append(data)

    return {'list': resp_items, 'page': query_dct.get('$page', 1),
            'total_count': total_count, 'size': len(resp_items),
            'bet_total': bet_total, 'award_total': award_total}


@require_GET
@response_wrapper
@token_required
def get_casino_records(req):
    query_dct = req.GET.dict()
    game = query_dct.pop('game')
    if 'created_at' not in query_dct and 'user_id' not in query_dct and 'id' not in query_dct:
        today = tz.local_now().strftime('%Y-%m-%d')
        query_dct['created_at'] = '{"$gte":"' + today +\
                                  ' 00:00:00","$lt":"'+today+' 23:59:59"}'
    elif 'user_id' not in query_dct and 'id' not in query_dct:
        created_at = eval(query_dct['created_at'])
        start_date = datetime.datetime.strptime(created_at['$gte'][0:10], "%Y-%m-%d")
        end_date = datetime.datetime.strptime(created_at['$lt'][0:10], "%Y-%m-%d")
        if 7 < (end_date - start_date).days:
            raise ParamError(u'时间区间大于7天')

    if game == "lottery":
        return get_casino_records_lotter(query_dct)
    elif game == "bull":
        return get_casino_records_bull(query_dct)
    elif game == "kfc":
        return get_casino_records_kfc(query_dct)
    elif game == "fruit":
        return get_casino_records_fruit(query_dct)
    
    return {"error": "game is null or not right!"}
